﻿using CaseManagerLibrary.Http;
using CaseManagerLibrary.Models;
using Newtonsoft.Json;
using PSDLib.Models;
using PSDManager.SystemSettings.DeviceTree;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PSDManager.SystemSettings.RouteSetting
{
    public partial class RouteMap : UserControl
    {
        public class RouteMapDesignContext
        {
            public string MapId { get; set; }
            public bool EditMode { get; set; }
            public Point CameraInitLocation { get; set; }
            public int LastX { get; set; }
            public int LastY { get; set; }
            public bool DragCamera { get; set; }
            public RouteChannel CurrCamera { get; set; }

            public RouteMapDesignContext()
            {
                EditMode = false;
                DragCamera = false;
            }
        }



        internal bool map_loading = false;

        private string currRouteId = "";
        private string mapId = "";

        public RouteMapDesignContext DesignContext { get; set; }

        public List<dl_route_config_vo> routeConfigList { get; set; }

        private List<dl_server_config> serverConfig;

        public RouteMap()
        {
            InitializeComponent();
        }

        public void Init(string mapid, string routeId, string routeName)
        {
            mapId = mapid;
            currRouteId = routeId;
            this.lblRoute.Text = "路径方案：" + routeName;

            DesignContext = new RouteMapDesignContext();
            DesignContext.MapId = mapId;

            palMap.ContextMenuStrip = null;

            this.Size = new Size(1240, 776);

            ResourceManager rm = new ResourceManager("PSDManager.Properties.Resources", typeof(Properties.Resources).Assembly);
            palMap.BackgroundImage = (Image)rm.GetObject(mapId);
            palMap.BackgroundImageLayout = ImageLayout.Center;

            this.FindForm().ClientSize = this.Size;

            GetCameras();

            SetSelectedCamerea(currRouteId);
        }

        public void SetSelectedCamerea(string routeId)
        {
            currRouteId = routeId;

            var result = HttpHelper.Get<HResult<List<dl_route_config_vo>>>(AppSettings.Setting.API.GetRouteConfigListById + "?routeId=" + routeId);

            if (result.success)
            {
                routeConfigList = result.data;

                foreach (var ch in result.data)
                {
                    var camera = (palMap.Controls.Find("camera_" + ch.server_id + "_" + ch.channel_id, false)[0] as RouteChannel);

                    if (camera != null)
                    {
                        camera.Selected = true;
                    }
                }
            }

            map_loading = false;
        }

        private void btnAddCamera_Click(object sender, EventArgs e)
        {
            //cmCamera.Visible = !cmCamera.Visible;
            if (!DesignContext.EditMode)
            {
                palMap.ContextMenuStrip = cmCamera;

                btnSetCamera.Text = "结束点位配置";
            }
            else
            {
                palMap.ContextMenuStrip = null;

                btnSetCamera.Text = "配置摄像机点位";
            }

            DesignContext.EditMode = !DesignContext.EditMode;

        }

        private void miAddCamera_Click(object sender, EventArgs e)
        {
            FrmChannelSelector frm = new FrmChannelSelector();
            frm.CameraSelected += Frm_CameraSelected;
            frm.ShowDialog();
        }

        private void Frm_CameraSelected(PSDLib.Download.ChannelInfo channel, dl_server_config server)
        {
            if (channel != null && server != null)
            {
                var c = palMap.Controls.Find("camera_" + server.id + "_" + channel.Id, false);

                if (c.Length == 0)
                {
                    dl_map_channel camera = new dl_map_channel();
                    camera.id = Guid.NewGuid().ToString();
                    camera.channel_id = channel.Id;
                    camera.channel_name = channel.Name;
                    camera.channel_desc = channel.Name;
                    camera.server_id = server.id;
                    camera.pos_x = DesignContext.CameraInitLocation.X;
                    camera.pos_y = DesignContext.CameraInitLocation.Y;
                    camera.map_id = DesignContext.MapId;

                    AddCamera(camera);
                }
                else
                {
                    MessageBox.Show("摄像机【" + channel.Name + "】已存在，请重新选择!");
                }
            }
        }

        private void palMap_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                DesignContext.CameraInitLocation = new Point(e.X, e.Y);
            }
        }

        private void GetCameras()
        {
            map_loading = true;

            var result_server = HttpHelper.Get<HResult<List<dl_server_config>>>(AppSettings.Setting.API.GetDownloadServerConfig);
            if (result_server.success)
            {
                serverConfig = result_server.data;
            }

            var result = HttpHelper.Get<HResult<List<dl_map_channel>>>(AppSettings.Setting.API.GetMapChannelList);

            if (result.success)
            {
                foreach (var ch in result.data)
                {
                    var camera = CreateCamera(ch.channel_id, ch.channel_desc, ch.server_id, new Point(ch.pos_x.Value, ch.pos_y.Value));
                    camera.Channel = ch;
                }
            }
        }

        private RouteChannel CreateCamera(string channelId, string channelDesc, string serverId, Point pos)
        {
            var camera = new RouteChannel();
            camera.Name = "camera_" + serverId + "_" + channelId;
            camera.Map = this;
            camera.Location = pos;
            camera.CameraId = channelId;
            camera.CameraName = channelDesc;
            camera.ServerId = serverId;
            camera.SelectChanged += Camera_SelectChanged;
            camera.EndDrag += Camera_EndDrag;
            palMap.Controls.Add(camera);
            camera.BringToFront();

            return camera;
        }

        private void AddCamera(dl_map_channel camera)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.AddMapChannel, JsonConvert.SerializeObject(camera));

            if (result.success)
            {
                DesignContext.CurrCamera = CreateCamera(camera.channel_id, camera.channel_desc, camera.server_id, new Point(camera.pos_x.Value, camera.pos_y.Value));
                DesignContext.CurrCamera.Channel = camera;
            }
            else
            {
                MessageBox.Show("添加摄像机点位失败！" + result.message);
            }
        }

        private void Camera_EndDrag(RouteChannel rc)
        {
            rc.Channel.pos_x = rc.Left;
            rc.Channel.pos_y = rc.Top;

            UpdateCamera(rc);
        }

        private void Camera_SelectChanged(RouteChannel rc)
        {
            if (!DesignContext.EditMode)
            {
                EnableCamera(rc);
            }
        }

        private void EnableCamera(RouteChannel rc)
        {
            var ch = routeConfigList.Where(t => t.channel_id == rc.Channel.channel_id && t.server_id == rc.Channel.server_id).FirstOrDefault();

            if (rc.Selected)
            {
                if (ch == null)
                {
                    ch = new dl_route_config_vo();
                    ch.id = Guid.NewGuid().ToString();
                    ch.channel_id = rc.Channel.channel_id;
                    ch.channel_name = rc.Channel.channel_desc;
                    ch.route_id = currRouteId;
                    ch.server_id = rc.Channel.server_id;

                    var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.AddRouteConfig, JsonConvert.SerializeObject(ch));

                    if (result.success)
                    {
                        routeConfigList.Add(ch);
                    }
                    else
                    {
                        MessageBox.Show("启用路径摄像机失败！" + result.message);
                    }
                }
            }
            else
            {
                if (ch != null)
                {
                    var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.DeleteRouteConfig,
                        new Dictionary<string, string> {
                                {"routeId", currRouteId },
                                {"channelId", rc.Channel.channel_id },
                                {"serverId", ch.server_id }
                    });

                    if (result.success)
                    {
                        routeConfigList.Remove(ch);
                    }
                    else
                    {
                        MessageBox.Show("停用路径摄像机失败！" + result.message);
                    }
                }
            }
        }

        private void UpdateCamera(RouteChannel rc)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.UpdateMapChannel, JsonConvert.SerializeObject(rc.Channel));

            if (!result.success)
            {
                MessageBox.Show("更新摄像机点位失败！" + result.message);
            }
        }

        private void DeleteCamera(RouteChannel rc)
        {
            var result = HttpHelper.Post<HResult>(AppSettings.Setting.API.DeleteMapChannel,
                new Dictionary<string, string> {
                        {"channelId", rc.Channel.id }
                    });

            if (!result.success)
            {
                MessageBox.Show("删除摄像机点位失败！" + result.message);
            }
            else
            {
                palMap.Controls.Remove(rc);
            }
        }

        private void miDeleteCamera_Click(object sender, EventArgs e)
        {
            if (DesignContext.EditMode && DesignContext.CurrCamera != null)
            {
                if (MessageBox.Show("是否确定删除【" + DesignContext.CurrCamera.CameraName + "】？", "提示",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DeleteCamera(DesignContext.CurrCamera);
                }
            }
        }

        private void palMap_MouseDown(object sender, MouseEventArgs e)
        {
            if (DesignContext.EditMode && DesignContext.CurrCamera != null)
            {
                if (DesignContext.CurrCamera.Left > e.X || (DesignContext.CurrCamera.Left + DesignContext.CurrCamera.Width) < e.X
                    || DesignContext.CurrCamera.Top > e.Y || DesignContext.CurrCamera.Top + DesignContext.CurrCamera.Height >= e.Y)
                {
                    DesignContext.CurrCamera = null;
                }
            }
        }

        private void miReName_Click(object sender, EventArgs e)
        {
            if (DesignContext.CurrCamera != null)
            {
                var server = serverConfig.Where(t => t.id == DesignContext.CurrCamera.Channel.server_id).FirstOrDefault();
                FrmRenameCamera frm = new FrmRenameCamera();
                frm.StartPosition = FormStartPosition.CenterParent;
                frm.SetChannel(DesignContext.CurrCamera, server);
                frm.ShowDialog();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < palMap.Controls.Count; i++)
            {
                if ((palMap.Controls[i] as RouteChannel).CameraName.StartsWith(txtSearch.Text.Trim()))
                {
                    (palMap.Controls[i] as RouteChannel).Highlight = true;
                }
                else
                {
                    (palMap.Controls[i] as RouteChannel).Highlight = false;
                }
            }
        }

        private void btnResetSearch_Click(object sender, EventArgs e)
        {
            this.txtSearch.Text = "";

            for (int i = 0; i < palMap.Controls.Count; i++)
            {
                (palMap.Controls[i] as RouteChannel).Highlight = false;
            }
        }
    }
}
